package com.yingpai.fitness.service;

import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import com.yingpai.fitness.dvp_2_0.main.widget.ClearableEditText;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
=================================================
*作者:
*邮箱: remebermelula@aliyun.com
*时间: 2018/2/23
*类名:  SmsContentObserver .java
*版本: V 1.0
*描述:短信内容 观察者  这里用来进行读取指定的短信验证码   免去用户手动输入
 * 6.0系统以上需要获取读取短信的权限  才可以正常进行
===============================================
*/


public class SmsContentObserver extends ContentObserver {
//内容提供者
    public  static final String SMS_URL_INBOX=
            "content://sms/inbox";

    //Activity activity
    private Activity activity;
    //验证码编辑框
    private ClearableEditText et_verification_code;

    //读取短信指定号码
    private String phone_center="1069054086791620";

    //集合  用户暂时存储数据
  private ArrayList list = new ArrayList();
    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    public SmsContentObserver(Handler handler, Activity activity, ClearableEditText et_verification_code) {
        super(handler);
        this.activity=activity;
        this.et_verification_code=et_verification_code;
    }


    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Cursor cursor=null;
        //读取收件箱  指定号码的短信
        cursor=activity.managedQuery(Uri.parse(SMS_URL_INBOX)
                ,new String[]{"_id","address","body","read"}
                ,"address=? and read=?"
                , new String[]{phone_center,"0"},"date desc");

        if (cursor != null) {

            if (cursor.moveToFirst()) {
                String smsBody=cursor.getString(cursor.getColumnIndex("body"));
                System.out.println("smsbody=============================");
                String pattern="[1-9]\\d*";
                Pattern pattern1= Pattern.compile(pattern);
                Matcher matcher=pattern1.matcher(smsBody.toString());

                while (matcher.find()){

                    list.add(matcher.group());
                }


                if (!list.isEmpty()) {
                    et_verification_code.setText(list.get(0).toString());
                }




            }
        }
    }



}
